<template>
  <view class="content">
    <view class="title">{{ goodInfo.title }}</view>
    <view class="title_desc">
      <view class="type">{{ goodInfo.type }}</view>
      <view class="auth">{{ goodInfo.auth }}</view>
      <view class="auth_di">{{ goodInfo.area }}</view>
      <view style="color: #bdbdbd;">{{ goodInfo.createTime }}</view>
    </view>
    <view v-if="fujianExit" @click="shareFile"
          style="height: 120rpx;width: 700rpx; aqua; border-top: solid 1rpx #d6d6d6;border-bottom: solid 1rpx #d6d6d6;margin-left: 25rpx;margin-right: 25rpx;margin-top: 25rpx;display: flex;justify-content: start;align-items: center;">
      <view style="width: 80rpx;height: 82rpx;margin-left: 26rpx;">
        <image src="../../static/pdf_icon.png" style="width: 100%;height: 100%;"></image>
      </view>
      <view style="margin-left: 8rpx;width: 380rpx;">{{ goodInfo.fujian }}</view>
      <view style="margin-left: 4rpx;width: 280rpx;" v-if="!isComplt">下载中 {{ pro }}</view>
      <view style="margin-left: 4rpx;width: 280rpx;" v-if="isComplt">下载完成</view>
    </view>
    <view class="title_arear">
      <mp-html :content="goodInfo.txt"/>
    </view>
    <view class="title_footer">
      <view>阅读</view>
      <view style="margin-left: 6rpx;">{{ goodInfo.userRead }}</view>
    </view>
  </view>
</template>

<script>
import config from '../../utils/config.js'
import request from '../../utils/request.js'

export default {
  data() {
    return {
      isActive01: true,
      goodInfo: null,
      id: null,
      fujianExit: false,
      fujianurl: '',
      fujian: '',
      imgPrex: config.imgPrefx,
      downloadTask: null, // 下载任务对象
      pro: '...',
      isComplt: false
    }
  },
  onLoad(option) {
    var _this = this;
    console.info("页面切换时传递的信息：", option)
    _this.id = option.id;
	_this.fullurl = option.url; // 用于分享到朋友圈时使用
    _this.queryList()
    // 设置一个每2000毫秒执行一次的定时器

    setInterval(function () {
      let pro = uni.getStorageSync("fileidprocess:" + _this.id);
      _this.pro = pro ? pro : '0%';

      if ("100.00%" === pro) {
        console.info("1111", pro)
        _this.isComplt = true;
      }
    }, 200);

  },
  created() {
  },
  onShareAppMessage(res) {
	  var _this = this;
    let pages = getCurrentPages(); //获取当前页面栈的信息
    let currentPage = pages[pages.length - 1]; //获取到当前页面栈中最后一个页面的索引
      if (res.from === 'button') {// 来自页面内分享按钮
        console.log(res.target)
      }
      return {
        title: _this.goodInfo.title,
        path: currentPage.route + `?id=${this.id}&share=${this.share}` //后面是路径上要传递的参数
      }
    },
	onShareTimeline(res) {
		var _this = this;
	  let pages = getCurrentPages(); //获取当前页面栈的信息
	  let currentPage = pages[pages.length - 1]; //获取到当前页面栈中最后一个页面的索引
	    if (res.from === 'button') {// 来自页面内分享按钮
	      console.log(res.target)
	    }
	    return {
	      title: _this.goodInfo.title,
	      path: currentPage.route + `?id=${this.id}&share=${this.share}`, //后面是路径上要传递的参数
		  imageUrl:_this.fullurl
	    }
	  },
  methods: {
    onShareClick() {
      uni.shareAppMessage({
        title: '分享标题',
        path: '/pages/index/index',
        imageUrl: '分享封面图',
        success: function () {
          console.log('分享成功')
        }
      })
    },
    queryList() {
      let _this = this;
      request({
        url: '/app/v1/wenzhang/detail/' + _this.id,
        method: "GET"
      }).then(res => {
        if (200 == res.code) {
          //res.data['createTime'] = _this.formatDateTime(_this.stringToDate(res.data.createTime));
          res.data['createTime'] = res.data.createTime;
          _this.goodInfo = res.data;
          if (res.data.fujian) {
            _this.fujianExit = true
            _this.fujian = res.data.fujian
            _this.fujianurl = res.data.fujianurl
          }
        } else {
          console.error('查询文章详情失败');
        }
      })
    },
    chooseStyle(event) {

    },
    shareFile() {
      var _this = this;
      var file4Wenzhang = uni.getStorageSync("fileid:" + _this.goodInfo.id);
      if (undefined != file4Wenzhang && '' != file4Wenzhang) {
        // 附件已经完成下载，开始执行预览
        uni.openDocument({
          filePath: file4Wenzhang,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功');
          }
        });
      } else {
        // 判断当前是否是在下载中
        const pk = "fileidprocess:" + _this.goodInfo.id;
        const procs = uni.getStorageSync(pk);
        if (undefined != procs && '' != procs) {
          console.warn("当前文件正在下载中->", _this.goodInfo.id)
          return;
        }
        const promise1 = new Promise((resolve, reject) => {
          var filename = _this.fujian;
          uni.showLoading({
            title: '附件下载中',
            mask: true
          })

          setTimeout(function () {
            uni.hideLoading();
          }, 2000);

          /**
           uni.showToast({
           title: '附件下载中',
           icon: 'none',
           mask: false,
           duration: 1500
           });
           **/
          // 标注当前附件正在加载中标记
          _this.downloadTask = uni.downloadFile({
            url: _this.imgPrex + _this.fujianurl,
            //filePath: `${uni.env.USER_DATA_PATH}/${我是自定义标题}.pdf`,
            //filePath: `${uni.env.USER_DATA_PATH}/${filename}.pdf`,
            filePath: `${uni.env.USER_DATA_PATH}/${filename}`,
            timeout: 120000,
            success: function (res) {
              uni.hideLoading()
              uni.showToast({
                title: '下载完成',
                icon: 'success',
                duration: 1000
              });
              uni.setStorageSync("fileid:" + _this.goodInfo.id, res.filePath)
              // 咱时屏蔽下载完成以后直接预览的功能
              //var filePath = res.filePath;
              //resolve(filePath)
            },
            fail: function (error) {
              console.info(error)
              uni.showToast({
                title: '下载失败',
                icon: 'error',
                duration: 3000
              });
              uni.clearStorageSync("fileid:" + _this.goodInfo.id)
              uni.clearStorageSync("fileidprocess:" + _this.goodInfo.id)
              console.info("附件下载失败->", _this.goodInfo.id)
            }
          })
          _this.downloadTask.onProgressUpdate((res) => {
            let pro = (res.totalBytesWritten / res.totalBytesExpectedToWrite * 100).toFixed(2) + '%';
            //console.log('下载进度' + res.progress);
            //console.log('已经下载的数据长度' + res.totalBytesWritten);
            //console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
            console.log('下载进度:-->' + pro);
            uni.setStorageSync("fileidprocess:" + _this.goodInfo.id, pro)

            // 满足测试条件，取消下载任务。
            /**
             if (res.progress > 50) {
             downloadTask.abort();
             }**/
          });
        });
        /**
         promise1.then(v => {
         uni.openDocument({
         filePath: v,
         showMenu: true,
         success: function(res) {
         console.log('打开文档成功');
         }
         });
         })**/
      }
    },
    stringToDate(dateString) {
      // "2023-04-01 12:30:00";
      // 假设 dateString 是 "YYYY-MM-DD HH:mm:ss" 格式
      // 这里我们需要将它转换为 "YYYY/MM/DD HH:mm:ss" 或其他 Date 构造函数能识别的格式
      // 但实际上，大多数现代浏览器都支持 "YYYY-MM-DD" 作为日期部分，所以我们可以直接尝试解析
      const [year, month, day, hour, minute, second] = dateString.split(/[- :]/);
      // 注意：月份在Date构造函数中是从0开始的，所以我们需要减去1
      return new Date(Date.UTC(year, month - 1, day, hour, minute, second));
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      let month = date.getMonth() + 1; // 月份是从0开始的
      let day = date.getDate();
      let hours = date.getHours();
      let minutes = date.getMinutes();

      // 确保月份、日期、小时和分钟都是两位数
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;

      // 返回格式化的字符串
      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    }
  }
}
</script>
<style>
/** 设置整个页面的背景色为白色 **/
page {
  background-color: #fff;
}

.title {
  margin-left: 25rpx;
  font-weight: 700;
  font-size: 42rpx;
}

.title_desc {
  display: flex;
  justify-content: start;
  align-items: center;
  margin-top: 25rpx;
  font-size: 30rpx;
  color: #d6d6d6;
  margin-right: 30rpx;
  margin-left: 30rpx;
  margin-right: 25rpx;
  height: 39rpx;
}

.type {
  width: 64rpx;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f2f2f2;
  color: #b4b4b4;
  border-radius: 4rpx;
  font-size: 26rpx;
}

.auth {
  color: #62688c;
  font-size: 30rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
}

.auth_di {
  color: #62688c;
  font-size: 30rpx;
  margin-right: 20rpx;
}

.title_arear {
  margin-top: 25rpx;
  margin-left: 25rpx;
  margin-right: 25rpx;
  padding-left: 25rpx;
  padding-right: 25rpx;
}

.title_footer {
  display: flex;
  margin-left: 25rpx;
  margin-top: 25rpx;
  padding-bottom: 50rpx;
  font-size: 30rpx;
  color: #d6d6d6;
}
</style>
